package com.xnj.testweb.common.Interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.xnj.testweb.common.annotation.NoLoginCheck;
import com.xnj.testweb.common.constants.Constants;
import com.xnj.testweb.common.exeception.CommonException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class TokenAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Class<?> clazz = method.getDeclaringClass();
            boolean ignore = false;

            // 判断类上或方法上是否使用了无需登录的注解
            if (method.isAnnotationPresent(NoLoginCheck.class) || clazz.isAnnotationPresent(NoLoginCheck.class)) {
                ignore = true;
            }

            // 如果使用注解，放行
            if (ignore) {
                return true;
            }

//            // 未使用注解，说明需要验证，判断是否有token
//            String token = request.getHeader("satoken");
//            System.out.println(token);


//            // 获取 token 方法
//            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
//            Object loginIdByToken = StpUtil.getLoginIdByToken(tokenInfo.getTokenValue());
//            if (null == loginIdByToken) {
//                throw new CommonException(Constants.NOLOGIN, "请先登录");
//            }

            // 使用 sa token 方法
            boolean login = StpUtil.isLogin();
            if (!login) {
                throw new CommonException(Constants.NOLOGIN, "请先登录");
            }

        }

        return true;
    }

}